import axios from 'axios';
import PDFMerger from 'pdf-merger-js/browser';

const getFile = url => {
  return new Promise((resolve, reject) => {
    const obj = {
      method: 'get',
      url,
      responseType: 'blob'
      // responseType: 'arraybuffer'
    };
    return axios(obj).then(data => {
      console.log(data);
      resolve(data.data);
    }).catch(error => {
      // console.log(1);
      reject(error.toString());
    });
  });
};

const batchPdfDownload = async(arr) => {
  try {
    const promisePDFUrlArr = arr.map((item) => {
      console.log(item);
      return getFile(item);
    });
    // console.log(promisePDFUrlArr);
    const merger = new PDFMerger();
    const resultsArr = await Promise.allSettled(promisePDFUrlArr);
    console.log(resultsArr);
    // return

    // 过滤出成功的请求
    const successfulPromises = resultsArr.filter(item => {
      return item.status === 'fulfilled';
    });
    console.log(resultsArr);
    for (const {value} of successfulPromises) {
      console.log(value);
      await merger.add(value);
    }

    console.log(successfulPromises);

    // console.log(merger);

    const mergedPdf = await merger.saveAsBlob();

    const strURl = await promiseFileReader(mergedPdf);
    const url = URL.createObjectURL(mergedPdf);
    console.log(url);
    console.log(strURl);
    return strURl
  } catch (error) {
    console.error(error);
  }
}

const promiseFileReader = (blorStr) => {
  return new Promise((res, rej) => {
    const reader = new FileReader();
    reader.readAsDataURL(blorStr);
    reader.onload = function(e) {
      console.log(e);
      // var dataURL = reader.result;
      res(reader.result);
    };
    reader.onerror = function(e) {
      // var dataURL = reader.result;
      rej(e);
    };
  });
};

export {
  batchPdfDownload
}
